#!/bin/sh

set -e
#set -x

#########################
# Configuration
#########################

. /usr/share/debconf/confmodule
if [ -f /usr/share/dbconfig-common/dpkg/postinst.mysql ]; then
  . /usr/share/dbconfig-common/dpkg/postinst.mysql

  extrasql=" CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"

  dbc_generate_include='template:/etc/xwiki/hibernate.cfg.xml'
  dbc_generate_include_perms='644'
  dbc_generate_include_args='-U -o template_infile=/usr/share/xwiki/templates/mysql/hibernate.cfg.xml'

  dbc_go xwiki $@

  # if they don't want our help, quit
  if [ "$dbc_install" != "true" ]; then exit 0; fi

  # find out if we're upgrading/reinstalling
  if [ "$dbc_oldversion" ]; then
    # read that little crumb left in config if we're reconfiguring
    db_get $dbc_package/internal/reconfiguring && reconfiguring="$RET"
    # and set it back to false
    db_reset $dbc_package/internal/reconfiguring
    # if not, we're definitely upgrading
    if [ "$reconfiguring" = "false" ]; then
        upgrading="yes"
    else
        db_get $dbc_package/dbconfig-reinstall && reinstall=$RET
        db_reset $dbc_package/dbconfig-reinstall
        # if they've said they don't want to reinstall stuff...
        if [ "$reinstall" = "false" ]; then exit 0; fi
    fi
  fi

  # don't perform the following block of code during upgrades
  if [ ! "$upgrading" ]; then
    # Allow creating new wikis (so new databases)
    # TODO: ask it in an install step

    # Get the host
    if [ ! "${dbc_dballow:-}" ]; then
        if [ ! "${dbc_dbserver:-}" ] || [ "$dbc_dbserver" = "localhost" ]; then
            l_dballow=localhost
        else
            l_dballow=`hostname`
        fi
    else
        l_dballow="$dbc_dballow"
    fi

    echo "allow $dbc_dbuser user to create new databases"
    dbc_mysql_exec_command "GRANT ALL PRIVILEGES ON *.* to $dbc_dbuser@'$l_dballow'"
  fi
fi
